﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Views;
using JiveMessenger.Models;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using JmShared;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;

namespace JiveMessenger.ViewModels
{
    public class ViewModelSettingsPage : ViewModelBaseEx
#if WINDOWS_PHONE_APP
, IFileOpenPickerContinuable
#endif

    {
        private INavigationService _navigationService;
        public RelayCommand RemoveAvatarCommand { get; set; }
        public RelayCommand AddAvatarCommand { get; set; }
        public RelayCommand CloseAddServerPopupCommand { get; set; }
        public RelayCommand RemoveServerCommand { get; private set; }
        public RelayCommand<string> AddServerCommand { get; private set; }
        public RelayCommand LogoutCommand { get; set; }

        public IEnumerable<int> AgeSource { get; private set; }
        public IEnumerable<int> CountSource { get; private set; }

        private IClient _currentClient;
        public IClient CurrentClient
        {
            get { return _currentClient; }
            set
            {
                if (_currentClient != value)
                {
                    Set(() => CurrentClient, ref _currentClient, value);
                }
            }
        }
        private string _avatar;
        public string Avatar
        {
            get { return _avatar; }
            set
            {
                if (_avatar != value)
                {
                    Set(() => Avatar, ref _avatar, value);
                }
            }
        }

        public AppSettings AppSettings
        {
            get
            {
                return AppSettings.Instance;
            }
        }

        private ObservableCollection<FontColor> _systemColors;
        public ObservableCollection<FontColor> SystemColors
        {
            get { return _systemColors; }
            set
            {
                if (_systemColors != value)
                {
                    Set(() => SystemColors, ref _systemColors, value);
                }
            }
        }

        private FontColor _selectedColor;
        public FontColor SelectedColor
        {
            get { return _selectedColor; }
            set
            {
                if (_selectedColor != value)
                {
                    Set(() => SelectedColor, ref _selectedColor, value);

                    CurrentClient.UserSettings.FontHexColor = StaticMethods.ColorToHexString(value.Brush.Color);
                }
            }
        }

        //public string RemoveServerIcon
        //{
        //    get
        //    {
        //        if (StaticSettings.CurrentTheme == PhoneTheme.Dark || StaticSettings.CurrentTheme == PhoneTheme.HighContrastDark)
        //        {
        //            return "/Assets/AppBar/ApplicationBar.Delete.png";

        //        }
        //        else
        //        {
        //            return "/Assets/AppBar/ApplicationBar.Delete.Black.png";
        //        }
        //    }
        //}

        //public string AddServerIcon
        //{
        //    get
        //    {
        //        if (StaticSettings.CurrentTheme ==  PhoneTheme.Dark || StaticSettings.CurrentTheme == PhoneTheme.HighContrastDark)
        //            return "/Assets/AppBar/ApplicationBar.Add.png";
        //        else
        //            return "/Assets/AppBar/ApplicationBar.Add.Black.png";
        //    }
        //}

        private IEnumerable<string> _themeSource;
        public IEnumerable<string> ThemeSource
        {
            get { return _themeSource; }
            set
            {
                if (_themeSource != value)
                {
                    Set(() => ThemeSource, ref _themeSource, value);
                }
            }
        }

        private bool _storeMessagesWhileOffline;
        public bool StoreMessagesWhileOffline
        {
            get { return _storeMessagesWhileOffline; }
            set
            {
                if (_storeMessagesWhileOffline != value)
                {
                    CurrentClient.UserSettings.StoreMessagesWhileOffline = value;
                    _storeMessagesWhileOffline = value;
                    RaisePropertyChanged("StoreMessagesWhileOffline");
                }
            }
        }

        private int _offlineMessageCountLimit;
        public int OfflineMessageCountLimit
        {
            get { return _offlineMessageCountLimit; }
            set
            {
                if (_offlineMessageCountLimit != value)
                {
                    CurrentClient.UserSettings.OfflineMessagesCountLimit = value;
                    Set(() => OfflineMessageCountLimit, ref _offlineMessageCountLimit, value);
                }
            }
        }

        private int _offlineMessageAgeLimit;
        public int OfflineMessageAgeLimit
        {
            get { return _offlineMessageAgeLimit; }
            set
            {
                if (_offlineMessageAgeLimit != value)
                {
                    CurrentClient.UserSettings.OfflineMessagesAgeLimit = value;
                    Set(() => OfflineMessageAgeLimit, ref _offlineMessageAgeLimit, value);
                }
            }
        }


        private int _selectedPivotItemIndex;
        public int SelectedPivotItemIndex
        {
            get { return _selectedPivotItemIndex; }
            set
            {
                if (_selectedPivotItemIndex != value)
                {
                    _selectedPivotItemIndex = value;
                    IsAddServerPopupOpen = false;
                    RaisePropertyChanged("SelectedPivotItemIndex");
                }
            }
        }

        private bool _isContentControlEnabled;
        public bool IsContentControlEnabled
        {
            get { return _isContentControlEnabled; }
            set
            {
                if (_isContentControlEnabled != value)
                {
                    _isContentControlEnabled = value;
                    RaisePropertyChanged("IsContentControlEnabled");
                }
            }
        }


        private bool _isAddServerPopupOpen;
        public bool IsAddServerPopupOpen
        {
            get { return _isAddServerPopupOpen; }
            set
            {
                if (_isAddServerPopupOpen != value)
                {
                    _isAddServerPopupOpen = value;
                    IsContentControlEnabled = !value;
                    RaisePropertyChanged("IsAddServerPopupOpen");
                }
            }
        }

        //private string _password;
        //public string Password
        //{
        //    get { return _password; }
        //    set
        //    {
        //        if (_password != value)
        //        {
        //            Set(() => Password, ref _password, value);
        //        }
        //    }
        //}


        public ViewModelSettingsPage(IClient currentClient, INavigationService navService)
        {
            _navigationService = navService;
            IsContentControlEnabled = true;
            CurrentClient = currentClient;
            AgeSource = Enumerable.Range(1, 24);
            CountSource = CreateCountSource();
            ThemeSource = CreateThemeSource();
            if (currentClient.UserSettings != null && currentClient.IsLoggedIn)
            {
                OfflineMessageAgeLimit = currentClient.UserSettings.OfflineMessagesAgeLimit.GetValueOrDefault(8);
                OfflineMessageCountLimit = currentClient.UserSettings.OfflineMessagesCountLimit.GetValueOrDefault(150);
                StoreMessagesWhileOffline = currentClient.UserSettings.StoreMessagesWhileOffline.GetValueOrDefault(true);
                SystemColors = new ObservableCollection<FontColor>(new AvailableColors());
                Color userColor = StaticMethods.HexStringToColor(CurrentClient.UserSettings.FontHexColor);
                var matchingSystemColor = SystemColors.FirstOrDefault(x => x.Brush.Color == userColor);
                if (matchingSystemColor != null)
                    SelectedColor = matchingSystemColor;
                else
                    SelectedColor = new FontColor(userColor.ToString(), new SolidColorBrush(userColor));

                UpdateAvatarFromSettings();
            }

            if (IsInDesignMode)
                return;
            //Task.Run(() =>
            //{
            //    this.Password = CredentialsManager.GetStoredPasswordForUser(AppSettings.UsernameSetting);
            //});
            RemoveServerCommand = new RelayCommand(RemoveServerCommandAction);
            AddServerCommand = new RelayCommand<string>(AddServerCommandAction);
            CloseAddServerPopupCommand = new RelayCommand(CloseAddServerPopupCommandAction);
            AddAvatarCommand = new RelayCommand(AddAvatarCommandAction);
            RemoveAvatarCommand = new RelayCommand(RemoveAvatarCommandAction);
            LogoutCommand = new RelayCommand(LogoutCommandAction);
            //Window.Current.Activated += Current_Activated;
        }

        private async void LogoutCommandAction()
        {
            //_currentClient.StopReconnectRetrying = true;
            //await _currentClient.Connection.Logout();
            //CredentialsManager.RemoveCredential(AppSettings.Instance.UsernameSetting);
            //AppSettings.Instance.UsernameSetting = "";

            _navigationService.NavigateTo("LoginPage",true);
        }

        private async void AddAvatarCommandAction()
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".bmp");
#if WINDOWS_PHONE_APP
            // Launch file open picker and caller app is suspended and may be terminated if required
            openPicker.PickSingleFileAndContinue();
#else
          StorageFile file  = await  openPicker.PickSingleFileAsync();
          ProcessAvatarImage(file);
#endif
        }

#if WINDOWS_PHONE_APP
        /// <summary>
        /// Handle the returned files from file picker
        /// This method is triggered by ContinuationManager based on ActivationKind
        /// </summary>
        /// <param name="args">File open picker continuation activation argment. It cantains the list of files user selected with file open picker </param>
        public void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            if (args.Files.Count > 0)
            {
                Debug.WriteLine("Picked photo: " + args.Files[0].Name);
                ProcessAvatarImage(args.Files[0]);
            }
            else
            {
                Debug.WriteLine("Operation cancelled.");
            }

        }
#endif

        private void ProcessAvatarImage(StorageFile file)
        {
            _navigationService.NavigateTo("CropImagePage", new Tuple<ImageCropType,StorageFile>(ImageCropType.Avatar,file));
        }

        private void RemoveAvatarCommandAction()
        {
            this.Avatar = "ms-appx:///Assets/Images/avatar_empty_120x120.png";
            if (this.CurrentClient.UserSettings.Avatar == null)
                this.CurrentClient.UserSettings.Avatar = new Avatar();
            this.CurrentClient.UserSettings.Avatar.Hash = "";
            this.CurrentClient.UserSettings.Avatar.Extension = "";
        }
        //void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        //{
        //    RefreshIcons();
        //}

        private void CloseAddServerPopupCommandAction()
        {
            IsAddServerPopupOpen = false;
        }

        private void AddServerCommandAction(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                List<string> serverListCopy = new List<string>(AppSettings.Instance.ServerListSetting);
                serverListCopy.Add(str);
                AppSettings.Instance.ServerListSetting = serverListCopy;
                AppSettings.Instance.ServerSetting = str;
            }
            IsAddServerPopupOpen = false;

        }


        private void RemoveServerCommandAction()
        {
            if (String.IsNullOrEmpty(AppSettings.Instance.ServerSetting))
                return;
            //if (MessageBox.Show("Are you sure?", string.Format("Delete {0}", this.AppSettings.ServerSetting), MessageBoxButton.OKCancel) == MessageBoxResult.OK)

            Messenger.Default.Send(new NotificationMessageAction<bool>(this, new JiveDialogQuery("Remove server?",string.Format("{0} will be deleted", AppSettings.Instance.ServerSetting)), "QueryDialog", (r) =>
            {
                if (r == true)
                {
                    List<string> serverListCopy = new List<string>(AppSettings.Instance.ServerListSetting);
                    serverListCopy.Remove(AppSettings.Instance.ServerSetting);
                    AppSettings.Instance.ServerListSetting = serverListCopy;
                    AppSettings.Instance.ServerSetting = serverListCopy.Count > 0 ? serverListCopy[0] : null;
                }
            }));




        }
        private IEnumerable<string> CreateThemeSource()
        {
            return new string[] { "Dark", "Light" };
        }
        private IEnumerable<int> CreateCountSource()
        {
            return new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250 };

        }
        internal void SaveSettingsToServer()
        {
            if (!CurrentClient.IsLoggedIn)
                return;
            CurrentClient.Connection.SendCommand(CurrentClient.UserSettings, ClientCommands.WpSettings);

        }
        public override void Cleanup()
        {
            base.Cleanup();
            SimpleIoc.Default.Unregister<ViewModelSettingsPage>(VmHelper.Locator.ViewModelSettingsPageKey);
            VmHelper.Locator.ViewModelSettingsPageKey = System.Guid.NewGuid().ToString();
        }
        //internal void RefreshIcons()
        //{
        //    RaisePropertyChanged("RemoveServerIcon");
        //    RaisePropertyChanged("AddServerIcon");
        //}
        internal void UpdateAvatarFromSettings()
        {
            if (CurrentClient.UserSettings != null && CurrentClient.CurrentUserInfo!=null && CurrentClient.UserSettings.Avatar != null)
                Avatar = string.Format("ms-appdata:///local/{0}/Avatars/{1}", CurrentClient.CurrentUserInfo.UserName, CurrentClient.UserSettings.Avatar.Hash + CurrentClient.UserSettings.Avatar.Extension);

        }
    }
}
